<template>
  <div class="create-component-list">
    <div v-if="props.type !== 'l-image'">
      <div  v-for="(item, index) in props.list" :key="index" @click="onItemClick(item)" class="component-item">
        <component :is="props.type" v-bind="item"></component>
      </div>
    </div>

    <StyledUploader v-if="props.type === 'l-image'" :show-uploaded="false" @success="onImageUploaded"></StyledUploader>

  </div>
</template>

<script lang="ts" setup name="ComponentList">
import { cloneDeep } from 'lodash-es'
import { v4 as uuidv4 } from 'uuid'
import { message } from 'ant-design-vue'
import { getImageDimensions } from '@/constant/helper'
import StyledUploader from '@/components/StyledUploader.vue'
import {imageDefaultProps} from 'p-test-comp-es'
interface propsType {
  // TODO 类型
  list: {}[]
  type: 'l-text' | 'l-image' | 'l-shape'
}
const props = defineProps<propsType>()
const emits = defineEmits(['on-item-click'])
const onItemClick = (data: Partial<TextDefaultProps & ImageComponentProps>) => {
  const componentData: ComponentData = {
    id: uuidv4(),
    name: props.type,
    props: cloneDeep(data)
  }
  emits('on-item-click', componentData)
}

const onImageUploaded = async (resp: UploadResp, file: File) => {
  
  const componentData: ComponentData = {
    id: uuidv4(),
    name: props.type,
    props: cloneDeep(imageDefaultProps)
  }
  message.success('图片上传成功')
  componentData.props.imgSrc = resp.data.urls[0]
  //componentData.props.imgSrc = URL.createObjectURL(file) //测试
  const { width } = await getImageDimensions(file)
  const maxWidth = 373
  componentData.props.width = `${width > maxWidth ? maxWidth : width}px`
  emits('on-item-click', componentData)
}
</script>

<style lang="scss" scoped>
.create-component-list {
  position: relative;
  text-align: center;
  min-height: 400px;
  margin-left: auto;
  margin-right: auto;
  .component-item {
    width: 100px;
    margin: 0 auto;
    margin-bottom: 15px;
    > * {
      position: static !important;
    }
  }

}
</style>
